<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*, java.util.*" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Verifying...</title>
</head>
<body>

<CENTER>
<h1> Graduate School Application </h1>
<h3> Verifying... </h3>
</CENTER>

<%

String url = "jdbc:postgresql://localhost:5432/Applications";
Connection conn = null;
Statement stmt = null;
PreparedStatement ps = null;
ResultSet rs = null;
String instruc = null;
int addid = 0, nameid=0, counid =0, degid =0, mainid = 0;


try {
	// Registering Postgresql JDBC driver
	Class.forName("org.postgresql.Driver");
	// Open a connection to the database	
	conn = DriverManager.getConnection(url,"postgres","postgres");
	// Create the statement
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                				ResultSet.CONCUR_UPDATABLE);

	session.setAttribute("visited",true);
	

	// make sure the username hasn't already been used
	String uName = request.getParameter("uName");

	boolean uErr = false, pErr = false, eErr = false;
	
	rs = stmt.executeQuery("SELECT user_name FROM users");
	while( rs.next() )
	{
		if( uName.equals(rs.getString("user_name")) )
		{
			session.setAttribute("usrErr", true);
			session.setAttribute("pwdErr", false);
			session.setAttribute("emailErr", false);
			uErr = true;
		}
	}
	
	// make sure password and retype password are the same
	String pwd = request.getParameter("pwd");
	String rpwd = request.getParameter("rpwd");
	
	if( !(pwd.equals(rpwd)) || pwd == "" )
	{
		session.setAttribute("pwdErr",true);
		session.setAttribute("usrErr",false);
		session.setAttribute("emailErr", false);
		pErr = true;
	}
	
	// make sure this user hasn't registered already (email exists)
	String email = request.getParameter("email");
	
	rs = stmt.executeQuery("SELECT Email FROM users");
	while( rs.next() )
	{
		if( email.equals(rs.getString("Email")) )
		{
			session.setAttribute("emailErr", true);
			session.setAttribute("usrErr", false);
			session.setAttribute("pwdErr", false);
			eErr = true;
		}
	}
	
	// if there has been error, bounce back to app. reg. page
	if( uErr || pErr || eErr )
	{
		response.sendRedirect("appReg.jsp");
	}
	
	// otherwise, move on to reg. conf. page	
	else
	{
		session.setAttribute("usrErr",false);
		session.setAttribute("pwdErr",false);
		session.setAttribute("emailErr", false);
		session.setAttribute("uName", uName);
		session.setAttribute("pwd", pwd);
		session.setAttribute("email", email);
		
		response.sendRedirect("regConf.jsp");
	}
	
} catch (SQLException e) 
{ 
	System.out.println(e);
}

// close connection
rs.close();
stmt.close();
conn.close();


%>

</body>
</html>